﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using  System.IO.Ports;
using System.Threading;
using Modbus.Device;//引用Modbus库命名空间

namespace ModbusRTU_Master
{
    //public static class CommonRes
    //{
    //    public static SerialPort serialPort;
    //}
    public partial class Form1 : Form
    {
        //public SerialPort serialPort = null;//定义全局变量，用于创建串口对象
        public static SerialPort serialPort = new SerialPort();

        public Form3 form3Instance; // 添加一个 Form3 的实例字段
        //public IModbusMaster master = null;//创建主站类型变量
        public static IModbusMaster master = null;//创建主站类型变量
        public enum RegisterAddress
        {
            IGBT_Current_Gain = 51, // 写寄存器地址
            Vdref             = 77,
            RatePower,
            Vdlvrt,
            Vdhvrt,
            InvT,
            Ucap_charge,
            Ucap_stop,
            Ucap_Dvr_quit,
            OverUdcPeak      = 85,
            OverUdcDly,
            UnderUdc,
            UnderUdcDly,
            IGBTOverIRms,
            IGBTOverIRmsDly  = 90,
            IGBTOverURms,
            IGBTOverURmsDly,
            IGBTFanLev,
            IGBTFanErrLev,
            SCRFanLev = 95,
            SCRanErrLev,
            ENVFanLev,
            ENVFanErrLev,
            OverSysIRms,
            OverSysIRmsDly = 100,
            OverIgbtIPeak,
            OverIIgbtDly,
            IgbtFaultDly,
            HWIgbtFaultDly,
            OverIcapRms = 105,
            OverIcapRmsDly,
            OverFreqAC,
            UnderFreqAC,
            OverUPake,
            OverUPakeDly,
            SCR_num,


            // 可以继续添加其他寄存器地址
        }
        public static RegisterAddress CurrentRegisterAddress;//定义枚举类型变量，用于选择要读取的寄存器地址
        public Form1()
        {
            InitializeComponent();
        }
        
        //bool isOpen = false;//串口是否打开
        public UserControl1 WinData1; //创建用户控件一变量
        public UserControl2 WinData2; //创建用户控件二变量
        public UserControl3 WinData3; //创建用户控件三变量

        private void button_OpenSerial_Click(object sender, EventArgs e)
        {

            //try
            //{
            //    // 将每个子字符串转换为 ushort 类型 
            //    for (int i = 0; i < strArray.Length; i++)
            //    {
            //        RWHoldingRegData[i] = ushort.Parse(strArray[i]);
            //    }
            //}
            //catch (FormatException)
            //{
            //    MessageBox.Show("Label 中的数据格式不正确，请确保是有效的 ushort 数字，并且以逗号分隔。");
            //}
            if (button_OpenSerial.Text == "打开串口")
            {
                try
                {
                    serialPort.Open();
                    button_OpenSerial.Text = "关闭串口";
                    textBox_SlaveID.Text = "1";//初始化为1
                    if (serialPort.IsOpen)
                    {
                        byte slaverId = byte.Parse(textBox_SlaveID.Text);//要转换为int类型就使用int.Parse（textBox_SlaveID.Text）
                        if (slaverId < 1 || slaverId > 247)
                        {
                            slaverId = 1;
                        }
                        //isOpen = true;//已连接串口
                        MessageBox.Show("串口打开成功！");
                        master = ModbusSerialMaster.CreateRtu(serialPort);//创建主站对象
                                                                          
                        //SomeMethod();// 启动后台任务读取寄存器
                        //ushort[] HoldingRegData = master.ReadHoldingRegisters(1, 0, 14);
                        //labelGridUaRms.Text = string.Join(",", HoldingRegData[8]);
                        //labelGridUbRms.Text = string.Join(",", HoldingRegData[9]);
                        //labelGridUcRms.Text = string.Join(",", HoldingRegData[10]);
                        //labelLoadIaRms.Text = string.Join(",", HoldingRegData[11]);
                        //labelLoadIbRms.Text = string.Join(",", HoldingRegData[12]);
                        //labelLoadIcRms.Text = string.Join(",", HoldingRegData[13]);
                    }
                    Task.Run
                    (() =>
                        {
                            while (serialPort.IsOpen)
                            {

                                //byte[] sendBytes = new byte[] { 0x01, 0x03, 0x00, 0x09, 0x00, 0x01, 0x54, 0x08, };
                                //serialPort.Write(sendBytes, 0, sendBytes.Length);
                                ushort[] HoldingRegData0 = master.ReadHoldingRegisters(1, 0, 100);

                                WinData1.Controls["labelGridUaRms"].Text = string.Join(",", HoldingRegData0[8]);
                                WinData1.Controls["labelGridUbRms"].Text = string.Join(",", HoldingRegData0[9]);
                                WinData1.Controls["labelGridUcRms"].Text = string.Join(",", HoldingRegData0[10]);
                                WinData1.Controls["labelLoadIaRms"].Text = string.Join(",", HoldingRegData0[11]);
                                WinData1.Controls["labelLoadIbRms"].Text = string.Join(",", HoldingRegData0[12]);
                                WinData1.Controls["labelLoadIcRms"].Text = string.Join(",", HoldingRegData0[13]);
                                WinData1.Controls["labelInvIaRms"].Text = string.Join(",", HoldingRegData0[14]);
                                WinData1.Controls["labelInvIbRms"].Text = string.Join(",", HoldingRegData0[15]);
                                WinData1.Controls["labelInvIcRms"].Text = string.Join(",", HoldingRegData0[16]);
                                WinData1.Controls["labelLoadIdp"].Text = string.Join(",", HoldingRegData0[17]);
                                WinData1.Controls["labelLoadIqp"].Text = string.Join(",", HoldingRegData0[18]);
                                WinData1.Controls["labelGridUdp"].Text = string.Join(",", HoldingRegData0[19]);
                                WinData1.Controls["label_LoadUaRms"].Text = string.Join(",", HoldingRegData0[20]);
                                WinData1.Controls["label_LoadUbRms"].Text = string.Join(",", HoldingRegData0[21]);
                                WinData1.Controls["label_LoadUcRms"].Text = string.Join(",", HoldingRegData0[22]);
                                WinData1.Controls["label_DCBusV"].Text = string.Join(",", HoldingRegData0[23]);
                                WinData1.Controls["label_LoadUqp"].Text = string.Join(",", HoldingRegData0[24]);
                                WinData1.Controls["label_LoadUdp"].Text = string.Join(",", HoldingRegData0[25]);
                                WinData1.Controls["label_GridIaRms"].Text = string.Join(",", HoldingRegData0[26]);
                                WinData1.Controls["label_GridIbRms"].Text = string.Join(",", HoldingRegData0[27]);
                                WinData1.Controls["label_GridIcRms"].Text = string.Join(",", HoldingRegData0[28]);
                                WinData1.Controls["label_CapIaRms"].Text = string.Join(",", HoldingRegData0[29]);
                                WinData1.Controls["label_CapIbRms"].Text = string.Join(",", HoldingRegData0[30]);
                                WinData1.Controls["label_CapIcRms"].Text = string.Join(",", HoldingRegData0[31]);
                                WinData1.Controls["label_Ugird_rms_filter"].Text = string.Join(",", HoldingRegData0[32]);
                                WinData1.Controls["label_Ucapf"].Text = string.Join(",", HoldingRegData0[33]);
                                WinData1.Controls["label_Igird_rms_filter"].Text = string.Join(",", HoldingRegData0[34]);
                                WinData1.Controls["label_ntc1"].Text = string.Join(",", HoldingRegData0[35]);
                                WinData1.Controls["label_ntc"].Text = string.Join(",", HoldingRegData0[36]);
                                WinData1.Controls["label_FluctuationCount"].Text = string.Join(",", HoldingRegData0[37]);
                                WinData1.Controls["label_SOFT_VERSION"].Text = string.Join(",", HoldingRegData0[38]);
                                WinData1.Controls["label_Year"].Text = string.Join(",", HoldingRegData0[39]);
                                WinData1.Controls["label_Month"].Text = string.Join(",", HoldingRegData0[40]);
                                WinData1.Controls["label_Day"].Text = string.Join(",", HoldingRegData0[41]);
                                WinData1.Controls["label_Hour"].Text = string.Join(",", HoldingRegData0[42]);
                                WinData1.Controls["label_Min"].Text = string.Join(",", HoldingRegData0[43]);
                                WinData1.Controls["label_Sec"].Text = string.Join(",", HoldingRegData0[44]);
                                WinData1.Controls["label_ActivePower"].Text = string.Join(",", HoldingRegData0[45]);
                                WinData1.Controls["label_ReactivePower"].Text = string.Join(",", HoldingRegData0[46]);
                                WinData1.Controls["label_PowerFactor"].Text = string.Join(",", HoldingRegData0[47]);
                                WinData1.Controls["label_ScrTempMax"].Text = string.Join(",", HoldingRegData0[48]);
                                WinData1.Controls["label_U_thd"].Text = string.Join(",", HoldingRegData0[49]);
                                WinData1.Controls["label_I_thd"].Text = string.Join(",", HoldingRegData0[50]);
                                WinData1.Controls["label_FrequencyA"].Text = string.Join(",", HoldingRegData0[53]);
                                WinData1.Controls["label_FrequencyB"].Text = string.Join(",", HoldingRegData0[54]);
                                WinData1.Controls["label_FrequencyC"].Text = string.Join(",", HoldingRegData0[55]);
                                WinData1.Controls["label_FaultsCount"].Text = string.Join(",", HoldingRegData0[56]);
                                WinData1.Controls["label_Invline_Vd"].Text = string.Join(",", HoldingRegData0[57]);

                                WinData1.Controls["label_GridUdp"].Text = string.Join(",", HoldingRegData0[60]);
                                WinData1.Controls["label_GridVdb"].Text = string.Join(",", HoldingRegData0[61]);
                                WinData1.Controls["label_GridVdc"].Text = string.Join(",", HoldingRegData0[62]);

                                //ushort[] RHoldingRegData = master.ReadWriteMultipleRegisters(1, 0, 53, 53,WHoldingRegData);
                                //ushort[] Data = { 1, 2, 3, 4, 5 };
                                //master.WriteMultipleRegisters(1, 53, WHoldingRegData);
                                //Thread.Sleep(1000);
                                //ushort[] RHoldingRegData = master.ReadHoldingRegisters(1, 0, 54);
                                WinData2.Controls["textBox_IGBT_Cur_gain_R"].Text = string.Join(",", HoldingRegData0[51]);
                                WinData2.Controls["textBox_Vdref"].Text           = string.Join(",", HoldingRegData0[77]);
                                WinData2.Controls["textBox_RatePower"].Text       = string.Join(",", HoldingRegData0[78]);
                                WinData2.Controls["textBox_Vdlvrt"].Text          = string.Join(",", HoldingRegData0[79]);
                                WinData2.Controls["textBox_Vdhvrt"].Text          = string.Join(",", HoldingRegData0[80]);
                                WinData2.Controls["textBox_InvT"].Text            = string.Join(",", HoldingRegData0[81]);
                                WinData2.Controls["textBox_Ucap_charge"].Text     = string.Join(",", HoldingRegData0[82]);
                                WinData2.Controls["textBox_Ucap_stop"].Text       = string.Join(",", HoldingRegData0[83]);
                                WinData2.Controls["textBox_Ucap_Dvr_quit"].Text   = string.Join(",", HoldingRegData0[84]);
                                WinData2.Controls["textBox_OverUdcPeak"].Text     = string.Join(",", HoldingRegData0[85]);
                                WinData2.Controls["textBox_OverUdcDly"].Text      = string.Join(",", HoldingRegData0[86]);
                                WinData2.Controls["textBox_UnderUdc"].Text        = string.Join(",", HoldingRegData0[87]);
                                WinData2.Controls["textBox_UnderUdcDly"].Text     = string.Join(",", HoldingRegData0[88]);
                                WinData2.Controls["textBox_IGBTOverIRms"].Text    = string.Join(",", HoldingRegData0[89]);
                                WinData2.Controls["textBox_IGBTOverIRmsDly"].Text = string.Join(",", HoldingRegData0[90]);
                                WinData2.Controls["textBox_IGBTOverURms"].Text    = string.Join(",", HoldingRegData0[91]);
                                WinData2.Controls["textBox_IGBTOverURmsDly"].Text = string.Join(",", HoldingRegData0[92]);
                                WinData2.Controls["textBox_IGBTFanLev"].Text      = string.Join(",", HoldingRegData0[93]);
                                WinData2.Controls["textBox_IGBTFanErrLev"].Text   = string.Join(",", HoldingRegData0[94]);
                                WinData2.Controls["textBox_SCRFanLev"].Text       = string.Join(",", HoldingRegData0[95]);
                                WinData2.Controls["textBox_SCRanErrLev"].Text     = string.Join(",", HoldingRegData0[96]);
                                WinData2.Controls["textBox_ENVFanLev"].Text       = string.Join(",", HoldingRegData0[97]);
                                WinData2.Controls["textBox_ENVFanErrLev"].Text    = string.Join(",", HoldingRegData0[98]);
                                WinData2.Controls["textBox_OverSysIRms"].Text     = string.Join(",", HoldingRegData0[99]);
                                Thread.Sleep(1000);
                                ushort[] HoldingRegData1 = master.ReadHoldingRegisters(1, 100, 100);
                                WinData2.Controls["textBox_OverSysIRmsDly"].Text  = string.Join(",", HoldingRegData1[0]);
                                WinData2.Controls["textBox_OverIgbtIPeak"].Text   = string.Join(",", HoldingRegData1[1]);
                                WinData2.Controls["textBox_OverIIgbtDly"].Text    = string.Join(",", HoldingRegData1[2]);
                                WinData2.Controls["textBox_IgbtFaultDly"].Text    = string.Join(",", HoldingRegData1[3]);
                                WinData2.Controls["textBox_HWIgbtFaultDly"].Text  = string.Join(",", HoldingRegData1[4]);
                                WinData2.Controls["textBox_OverIcapRms"].Text     = string.Join(",", HoldingRegData1[5]);
                                WinData2.Controls["textBox_OverIcapRmsDly"].Text  = string.Join(",", HoldingRegData1[6]);
                                WinData2.Controls["textBox_OverFreqAC"].Text      = string.Join(",", HoldingRegData1[7]);
                                WinData2.Controls["textBox_UnderFreqAC"].Text     = string.Join(",", HoldingRegData1[8]);
                                WinData2.Controls["textBox_OverUPake"].Text       = string.Join(",", HoldingRegData1[9]);
                                WinData2.Controls["textBox_OverUPakeDly"].Text    = string.Join(",", HoldingRegData1[10]);
                                WinData2.Controls["textBox_SCR_num"].Text         = string.Join(",", HoldingRegData1[11]);
                                Thread.Sleep(1000);
                            }
                        }
                    );
                }
                catch (Exception)
                {
                    MessageBox.Show("串口打开失败！");
                }
            }   
            else
            {
                try
                {
                    //isOpen = false;
                    serialPort.Close();//关闭串口
                }
                catch (Exception)
                {

                }
                button_OpenSerial.Text = "打开串口";
            }
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void label6_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            serialPort = new SerialPort("COM3", 19200, Parity.None, 8, StopBits.One);
            CheckForIllegalCrossThreadCalls = false;
            WinData1 = new UserControl1();
            WinData2 = new UserControl2();
            WinData3 = new UserControl3();
            //serialPort.DataReceived += serialPort_DataReceived;

        }

        //private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        //{
        //    //MessageBox.Show("串口接收到数据");
        //    int len = serialPort.ReadBufferSize;//固定值，指串口接收数据最大容量
        //    byte[] buff = new byte[len];
        //    serialPort.Read(buff, 0, len);
        //    int dataLen = buff[2];
        //    listBox1.Items.Add(buff[4]);
        //    //Encoding.BigEndianUnicode
        //}

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void labelTest_Click(object sender, EventArgs e)
        {

        }

        private void button_SerialSet_Click(object sender, EventArgs e)
        {
            Form2 Window2 = new Form2();
            Window2.ShowDialog();
        }

        private void button_WinData1_Click(object sender, EventArgs e)
        {
            WinData1.Show();
            panel1.Controls.Clear();
            panel1.Controls.Add(WinData1);
        }

        private void button_WinData2_Click(object sender, EventArgs e)
        {
            WinData2.Show();
            panel1.Controls.Clear();
            panel1.Controls.Add(WinData2);
        }
        private void panel1Paint(object sender, PaintEventArgs e)
        {

        }
        private void button_WinData3_Click(object sender, EventArgs e)
        {
            WinData3.Show();
            panel1.Controls.Clear();
            panel1.Controls.Add(WinData3);
        }

        private void button_WinData0_Click(object sender, EventArgs e)
        {
            WinData1.Hide();
            WinData2.Hide();
            WinData3.Hide();
        }

        private void button_Send_Click(object sender, EventArgs e)
        {
            form3Instance = new Form3();
            string labeIGBTCurgainText = form3Instance.TextBoxWriterValueText;//WinData2.Controls["textBox_IGBT_Cur_gain_S"].Text;
            //string labeIGBTCurgainText = WinData2.Controls["textBox_IGBT_Cur_gain_S"].Text;//读取输入框的值
            if (string.IsNullOrWhiteSpace(labeIGBTCurgainText))
            {
                MessageBox.Show("请输入值。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return; // 提前退出方法
            }
            ushort[] WHoldingRegData = new ushort[1];
            WHoldingRegData[0] = ushort.Parse(labeIGBTCurgainText);
            if (serialPort.IsOpen)
            {
                master.WriteMultipleRegisters(1, 53, WHoldingRegData);
            }    
            Thread.Sleep(500);
        }
    }
}
